package org.ims.inv.web.action.flow;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ims.inv.model.flow.ModelFlowDef;
import org.ims.inv.model.flow.ModelFlowTemplate;
import org.springframework.beans.BeanUtils;

import cn.trymore.core.exception.ServiceException;
import cn.trymore.core.log.LogAnnotation;
import cn.trymore.core.util.UtilString;
import cn.trymore.core.web.paging.PaginationSupport;
import cn.trymore.core.web.paging.PagingBean;

/**
 * Action: 工作流
 * 
 * @author Jeccy.Zhao
 *
 */
public class FlowDefIndexAction
extends FlowBaseAction
{
	/**
	 * The LOGGER
	 */
	private static final Logger LOGGER = Logger.getLogger(FlowDefIndexAction.class);
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 流程定义页面
	 */
	public ActionForward pageFlowDefIndex (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			ModelFlowDef formEntity = (ModelFlowDef) form;
			
			PagingBean pagingBean = this.getPagingBean(request);
			PaginationSupport<ModelFlowDef> result = 
				this.serviceWorkFlow.getServiceFlowDefinition().getPagination(formEntity, pagingBean);
			
			request.setAttribute("datagrid", result);
			request.setAttribute("formEntity", formEntity);
			
			// 输出分页信息至客户端
			outWritePagination(request, pagingBean, result);
			
		} 
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when fetch all flow definitions.", e);
		}
		
		
		return mapping.findForward("page.flow.def.index");
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 流程定义弹框
	 */
	public ActionForward dialogFlowDefPage (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String entityId = request.getParameter("id");
			if (UtilString.isNotEmpty(entityId))
			{
				if (this.isObjectIdValid(entityId))
				{
					request.setAttribute("entity", this.serviceWorkFlow.getServiceFlowDefinition().get(entityId));
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
				}
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
		
		return mapping.findForward("dialog.flow.def");
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 流程配置弹框
	 */
	public ActionForward dialogFlowDefConfPage (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String entityId = request.getParameter("id");
			if (UtilString.isNotEmpty(entityId))
			{
				if (this.isObjectIdValid(entityId))
				{
					ModelFlowDef entity = this.serviceWorkFlow.getServiceFlowDefinition().get(entityId);
					if (entity != null)
					{
						request.setAttribute("entity", entity);
					}
					else
					{
						return ajaxPrint(response, getErrorCallback("数据实体不存在!"));
					}
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
				}
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("数据ID未给定!"));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
		
		return mapping.findForward("dialog.flow.def.conf");
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 保存流程定义
	 */
	@LogAnnotation(description="流程定义新增或更新, `${defName}`",type="流程设置")
	public ActionForward actionSaveFlowDef (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			ModelFlowDef formEntity = (ModelFlowDef)form;
			ModelFlowDef entity = formEntity;
			
			boolean isActionEdit = this.isObjectIdValid(formEntity.getId());
			
			if (isActionEdit)
			{
				// 编辑
				entity = this.serviceWorkFlow.getServiceFlowDefinition().get(formEntity.getId());
				if (entity != null)
				{
					BeanUtils.copyProperties(formEntity, entity, new String[] { "defCreationTime", "templates" } );
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("权限数据实体不存在!"));
				}
			}
			else
			{
				entity.setDefCreationTime(new Date());
				
				this.initializationOnCreation(entity);
			}
			
			if (entity.getDefApplied().equals(ModelFlowDef.DEF_APPLIED))
			{
				ModelFlowDef activatedEntity = 
					this.serviceWorkFlow.getServiceFlowDefinition().getCurrentAppliedDefinition();
				
				if (activatedEntity != null && !activatedEntity.getId().equals(entity.getId()))
				{
					activatedEntity.setDefApplied(ModelFlowDef.DEF_DROPPED);
				}
				
				this.serviceWorkFlow.getServiceFlowDefinition().save(activatedEntity);
			}
			
			// 保存
			this.serviceWorkFlow.getServiceFlowDefinition().save(entity);
			
			return ajaxPrint(response, 
					getSuccessCallback("数据保存成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when saving flow definition data", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * 默认创建初审和复审两个环节...
	 * 
	 * @param def
	 */
	private void initializationOnCreation (ModelFlowDef def)
	{
		ModelFlowTemplate tplTrail = new ModelFlowTemplate();
		tplTrail.setConferenceFlag(0);
		tplTrail.setMandatoryFlag(1);
		tplTrail.setSequence(1);
		tplTrail.setNodeTitle(NODE_NAME_TRIAL);
		tplTrail.setNodeKey(NODE_KEY_TRIAL);
		tplTrail.setNodeDesc(null);
		
		ModelFlowTemplate tplReview = new ModelFlowTemplate();
		tplReview.setConferenceFlag(0);
		tplReview.setMandatoryFlag(1);
		tplReview.setSequence(2);
		tplReview.setNodeTitle(NODE_NAME_REVIEW);
		tplReview.setNodeKey(NODE_KEY_REVIEW);
		tplReview.setNodeDesc(null);
		
		def.appendTemplateDate(tplTrail);
		def.appendTemplateDate(tplReview);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 移除流程定义
	 */
	@LogAnnotation(description="流程定义移除, `${id}`",type="流程设置")
	public ActionForward actionRemoveFlowDef (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String defId = request.getParameter("id");
			if (this.isObjectIdValid(defId))
			{
				this.serviceWorkFlow.getServiceFlowDefinition().remove(defId);
				
				return ajaxPrint(response, 
					getSuccessCallbackAndReloadCurrent("数据删除成功."));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
			}
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when removing data", e);
			return ajaxPrint(response, getErrorCallback("数据删除失败,原因:" + e.getMessage()));
		}
		
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 激活流程定义
	 */
	@LogAnnotation(description="流程定义激活, `${id}`",type="流程设置")
	public ActionForward actionActivateFlowDef (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String defId = request.getParameter("id");
			if (this.isObjectIdValid(defId))
			{
				this.serviceWorkFlow.activateFlowDefinition(defId);
				
				return ajaxPrint(response, 
					getSuccessCallbackAndReloadCurrent("流程激活成功."));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
			}
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when activating data", e);
			return ajaxPrint(response, getErrorCallback("数据操作失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 摒弃流程定义
	 */
	@LogAnnotation(description="流程定义摒弃, `${id}`",type="流程设置")
	public ActionForward actionDropFlowDef (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String defId = request.getParameter("id");
			if (this.isObjectIdValid(defId))
			{
				this.serviceWorkFlow.dropFlowDefinition(defId);
				
				return ajaxPrint(response, 
					getSuccessCallbackAndReloadCurrent("流程摒弃成功."));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
			}
		}
		catch (ServiceException e)
		{
			LOGGER.error("Exception raised when dropping data", e);
			return ajaxPrint(response, getErrorCallback("数据操作失败,原因:" + e.getMessage()));
		}
	}
	
	public static Logger getLogger()
	{
		return LOGGER;
	}
	
}
